import asyncio
import re
from random import randint
from jinja2 import Template
from pyrogram import filters, Client
from pyrogram.types.messages_and_media import Message
from pyrogram.enums import ParseMode

from app import app, logger
from app.libs.data import add_gen, save_need
from app.filters import custom_filters
from app.reply_message import REPLY_MESSAGE
from config import (
    REDPOCKET_RETRY_COUNT,
    REDPOCKET_SLEEPTIME_MAX,
    REDPOCKET_SLEEPTIME_MIN,
)


TARGET = -1001833464786

redpockets = {}


async def in_redpockets_filter(_, __, m: Message):
    return bool(m.text in redpockets)


@app.on_message(
    filters.chat(TARGET)
    & custom_filters.choujiang_bot
    & filters.regex(r"^新的抽奖已经创建[\s\S]+参与关键词：「(.+)」")
)
async def choujiang(client: Client, message: Message):
    await asyncio.sleep(randint(10, 60))
    await client.send_message(
        message.chat.id,
        f"{message.matches[0].group(1)}",
        reply_to_message_id=message.reply_to_message_id,
    )


@app.on_message(
    filters.chat(TARGET)
    & custom_filters.zhuque_bot
    & custom_filters.reply_to_me
    & filters.regex(r"成功领取口令红包 (.+) 灵石")
)
async def get_redpocket_gen(client: Client, message: Message):
    gen = int(message.matches[0].group(1))
    data = await add_gen(gen)
    ret_str = f"""```红包 {message.reply_to_message.text} 领取成功
领取红包发送了{redpockets[message.reply_to_message.text]}次消息
成功领取口令红包 {gen} 灵石
今日领取口令红包 {data['today']} 灵石
累计领取口令红包 {data['total']} 灵石```"""
    logger.info(ret_str)
    await client.send_message("me", ret_str)
    del redpockets[message.reply_to_message.text]
    await message.reply_to_message.delete()


@app.on_message(
    filters.chat(TARGET)
    & custom_filters.zhuque_bot
    & filters.regex(r"该红包已领完")
    & filters.create(in_redpockets_filter)
)
async def redpocket_fail(client: Client, message: Message):
    ret = f"红包 {message.reply_to_message.text} 重试{redpockets[message.reply_to_message.text]}次，没领到，已经领完"
    logger.info(ret)
    await client.send_message("me", ret)
    del redpockets[message.reply_to_message.text]


@app.on_message(
    filters.chat(TARGET)
    & custom_filters.zhuque_bot
    & filters.regex(r"已创建口令红包:\n灵石: (\d+)\n数量: (\d+)\n口令: (.+)\n")
)
async def get_redpocket_message(client: Client, message: Message):
    global redpocket_message
    logger.info(f"有红包:{message.text}")
    match = message.matches[0]
    redpocket = int(match.group(1))
    number = int(match.group(2))
    string = match.group(3)
    if message.reply_to_message and message.reply_to_message.from_user.is_self:
        data = await add_gen(-redpocket)
        ret_str = f"""```红包 {string} 发送成功
发送口令红包消耗 {redpocket} 灵石
今日领取口令红包 {data['today']} 灵石
累计领取口令红包 {data['total']} 灵石```"""
        logger.info(ret_str)
        await client.send_message("me", ret_str)

    _match1 = re.search(r"^/redpocket (\d+) \d+ .+", string)
    _match2 = re.search(r"^/title .+", string)
    _match3 = re.search(r"^/itsmyturn(\d*).*", string)
    if _match1:
        if int(_match1.group(1)) >= int(redpocket / number):
            logger.info(f"红包:{string}被/redpocket过滤")
            return
    if _match2:
        logger.info(f"红包:{string}被/title过滤")
        return
    if _match3:
        turn = int(_match3.group(1) or 1)
        if turn * 1000 >= int(redpocket / number):
            logger.info(f"红包:{string}被/itsmyturn过滤")
            return

    logger.info(f"朱雀红包:{string}没被过滤")
    redpockets[string] = 0
    while string in redpockets:
        if redpockets[string] < REDPOCKET_RETRY_COUNT:
            redpockets[string] += 1
            logger.info(f"朱雀红包:发送 {string} 第{redpockets[string]}次")
            redpocket_message = await client.send_message(
                message.chat.id, string, ParseMode.DISABLED
            )
            await asyncio.sleep(
                randint(REDPOCKET_SLEEPTIME_MIN, REDPOCKET_SLEEPTIME_MAX)
            )
            await redpocket_message.delete()
        else:
            await client.send_message(
                "me", f"口令'{string}'重复发{REDPOCKET_RETRY_COUNT}次没有抢到"
            )
            break


@app.on_message(
    filters.chat(TARGET)
    & custom_filters.reply_to_me
    & custom_filters.zhuque_bot
    & filters.regex(r"修改完毕, 消费 \d+ 灵石。")
)
async def redpocket_edit_title(client: Client, message: Message):
    match = re.search(r"修改完毕, 消费 (\d+) 灵石。", message.text)
    if match:
        gen = int(match.group(1))
        data = await add_gen(-gen)
        ret_str = f"""```修改title消耗 {gen} 灵石
今日领取口令红包 {data['today']} 灵石
累计领取口令红包 {data['total']} 灵石```"""
        await client.send_message("me", ret_str)


@app.on_message(
    filters.chat(TARGET) & custom_filters.reply_to_me & filters.regex(r"/info.*")
)
async def look_my_info(client: Client, message: Message):
    reply_message = Template(REPLY_MESSAGE["look_my_info"]).render(message=message)
    sended_message = await client.send_message(
        message.chat.id, reply_message, reply_to_message_id=message.id
    )
    await asyncio.sleep(30)
    await sended_message.delete()


@app.on_message(filters.chat(TARGET) & custom_filters.auth & filters.command("fee"))
async def fee(client: Client, message: Message):
    ls = message.command[1]
    sended_message = await client.send_message(
        message.chat.id, f"+{ls}", reply_to_message_id=message.id
    )
    await asyncio.sleep(1)
    await sended_message.delete()


@app.on_message(filters.chat(TARGET) & filters.me & filters.command("train_days"))
async def get_redpocket_gen(client: Client, message: Message):
    from libs.request import get_list, deal_genshin_character_list_data

    await client.edit_message_text(message.chat.id, message.id, "```\n生成中...```")
    listGenshinCharacter = await get_list()
    cost, total, magic = deal_genshin_character_list_data(listGenshinCharacter)
    await save_need(total - cost)
    await client.edit_message_text(
        message.chat.id,
        message.id,
        f"```\n满级需要灵石：{total}\n升级消耗灵石：{cost}\n剩余所需灵石：{total - cost}\n每日灵石收益：{magic}\n升级还需要：{int((total - cost) / magic)}天```",
    )
    await asyncio.sleep(30)
    await message.delete()
